package com.df.tv.launcher.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import com.df.tv.launcher.R;

public class PointsView extends LinearLayout {
    private ImageView[] mPoints;
    private int mPosition = -1;
    private int mOldPosition = -1;
    private Context mContext;

    public PointsView(Context context) {
        super(context);
        mContext = context;
        init(context, 5);
    }

    public PointsView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        TypedArray styles = context.obtainStyledAttributes(attrs, R.styleable.points);
        int pointNum = styles.getInt(R.styleable.points_num, 5);
        init(context, pointNum);
    }

    private void init(Context context, int pointNum) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View mPointsView = inflater.inflate(R.layout.points, this);
        LinearLayout linearLayout = (LinearLayout) mPointsView.findViewById(R.id.layout_points);
        LinearLayout.LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        params.gravity = Gravity.CENTER_VERTICAL;
        mPoints = new ImageView[pointNum];
        for (int i = 0; i < pointNum; i++) {
            ImageView imageView = new ImageView(context);
            imageView.setScaleType(ScaleType.CENTER);
            imageView.setImageDrawable(context.getResources().getDrawable(R.drawable.switch_point_unfocsed));
            linearLayout.addView(imageView, params);
            mPoints[i] = imageView;
        }
    }

    public ImageView[] getPoints() {
        return mPoints;
    }

    public int getPosition() {
        return mPosition;
    }

    public void setPosition(int position) {
        switchPoint(position, mOldPosition);
        mOldPosition = position;
    }

    private void switchPoint(int newPos, int oldPos) {
        if (oldPos >= 0 && oldPos < mPoints.length) {
            mPoints[oldPos]
                    .setBackgroundDrawable(mContext.getResources().getDrawable(R.drawable.switch_point_unfocsed));
        }
        if (newPos >= 0 && newPos < mPoints.length) {
            mPoints[newPos].setBackgroundDrawable(mContext.getResources().getDrawable(R.drawable.switch_point_focsed));
        }
    }

}
